<template>
  <div v-if="showDebug" class="debug-panel">
    <div class="debug-header">
      <h3>🔧 调试面板</h3>
      <button @click="showDebug = false" class="close-btn">×</button>
    </div>
    
    <div class="debug-section">
      <h4>配置状态</h4>
      <div :class="['status-item', configStatus.isValid ? 'success' : 'error']">
        <span class="status-icon">{{ configStatus.isValid ? '✅' : '❌' }}</span>
        <span>配置验证: {{ configStatus.isValid ? '通过' : '失败' }}</span>
      </div>
      <div v-if="!configStatus.isValid" class="error-details">
        <ul>
          <li v-for="error in configStatus.errors" :key="error">{{ error }}</li>
        </ul>
      </div>
    </div>

    <div class="debug-section">
      <h4>API状态</h4>
      <div class="status-item">
        <span class="status-icon">🌐</span>
        <span>工作表ID: {{ worksheetId || '未配置' }}</span>
      </div>
      <div class="status-item">
        <span class="status-icon">👁️</span>
        <span>视图ID: {{ viewId || '未配置' }}</span>
      </div>
      <div class="status-item">
        <span class="status-icon">🔑</span>
        <span>AppKey: {{ appKey ? '已配置' : '未配置' }}</span>
      </div>
    </div>

    <div class="debug-section">
      <h4>字段映射</h4>
      <div class="field-list">
        <div v-for="(value, key) in fieldMapping" :key="key" 
             :class="['field-item', value ? 'configured' : 'missing']">
          <span class="field-name">{{ key }}</span>
          <span class="field-value">{{ value || '未配置' }}</span>
          <span class="field-status">{{ value ? '✅' : '❌' }}</span>
        </div>
      </div>
    </div>

    <div class="debug-section">
      <h4>未配置变量（来自 mdye.env.config）</h4>
      <div v-if="missingConfigKeys.length === 0" class="status-item success">
        <span class="status-icon">✅</span>
        <span>所有关键参数均已配置</span>
      </div>
      <div v-else class="missing-list">
        <div class="missing-item" v-for="item in missingConfigKeys" :key="item.id">
          <span class="missing-id">{{ item.id }}</span>
          <span class="missing-tip">未配置</span>
        </div>
      </div>
      <div class="configured-list" v-if="configuredConfigKeys.length">
        <h5>已配置（预览）</h5>
        <div class="configured-item" v-for="item in configuredConfigKeys" :key="item.id">
          <span class="cfg-id">{{ item.id }}</span>
          <span class="cfg-value">{{ item.preview }}</span>
        </div>
      </div>
    </div>

    <div class="debug-section">
      <h4>API测试</h4>
      <button @click="testConnection" :disabled="testing" class="test-btn">
        {{ testing ? '测试中...' : '测试连接' }}
      </button>
      <div v-if="testResult" :class="['test-result', testResult.success ? 'success' : 'error']">
        {{ testResult.message }}
      </div>
    </div>

    <div class="debug-section">
      <h4>最近搜索日志</h4>
      <div class="logs">
        <div v-for="log in recentLogs" :key="log.id" 
             :class="['log-item', log.type]">
          <span class="log-time">{{ formatTime(log.timestamp) }}</span>
          <span class="log-message">{{ log.message }}</span>
        </div>
      </div>
    </div>
  </div>
  
  <!-- 隐藏的调试按钮，开发者可通过键盘快捷键激活 -->
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { MINGDAO_CONFIG, validateConfig } from '../../config/mingdao-config.js';

// 读取运行时配置根（与 mingdao-config 中逻辑保持一致）
function getEnvRoot() {
  if (typeof window === 'undefined') return null;
  const candidates = [
    // 标准 mdye 环境
    () => window?.mdye?.env?.config,
    () => window?.mdye?.env,
    () => window?.env,
    // 明道云插件环境（根据错误信息添加）
    () => window?.ming_config,
    () => window?.parent?.ming_env?.config,
    () => window?.parent?.ming_config,
    () => window?.top?.ming_env?.config,
    () => window?.top?.ming_config,
    // 原有的父级环境
    () => window?.parent?.mdye?.env?.config,
    () => window?.top?.mdye?.env?.config,
    // 其他可能的环境
    () => window?.config,
    () => window?.parent?.config,
    () => window?.top?.config
  ];
  for (const getter of candidates) {
    try {
      const val = getter();
      if (val && typeof val === 'object') {
        console.log('找到环境配置:', val);
        return val;
      }
    } catch (_) {}
  }
  console.warn('未找到任何有效的环境配置');
  return null;
}

const showDebug = ref(false);
const testing = ref(false);
const testResult = ref(null);
const recentLogs = ref([]);
let logIdCounter = 0;

// 配置状态
const configStatus = computed(() => validateConfig());
const worksheetId = computed(() => MINGDAO_CONFIG.api.worksheetId);
const viewId = computed(() => MINGDAO_CONFIG.api.viewId);
const appKey = computed(() => MINGDAO_CONFIG.api.appKey);
const fieldMapping = computed(() => MINGDAO_CONFIG.fieldMapping);

// 关键变量清单（固定变量ID，无兼容性）
const requiredKeys = [
  // 基础认证
  'AppKey', 'Sign', 'apiAddress',
  // 工作表与视图
  'INVENTORY', 'INVENTORY_DEFAULT',
  'LOCATION_STOCK', 'LOCATION_STOCK_DEFAULT',
  'TRANSFER_ORDERS', 'TRANSFER_ORDERS_DEFAULT', 
  'LOCATION_MANAGEMENT', 'LOCATION_MANAGEMENT_DEFAULT',
  // 商品字段
  'PRODUCT_FIELDS.NAME', 'PRODUCT_FIELDS.BARCODE', 'PRODUCT_FIELDS.SUPPLIER',
  'PRODUCT_FIELDS.BATCH_CODE', 'PRODUCT_FIELDS.PRODUCTION_DATE',
  // 库存字段
  'STOCK_FIELDS.AVAILABLE', 'STOCK_FIELDS.LOCKED', 'STOCK_FIELDS.TOTAL',
  // 库位字段
  'LOCATION_FIELDS.CODE',
  // webhook
  'webhookUrl'
];

function pickPreview(value) {
  if (!value) return '';
  const str = String(value);
  if (str.length <= 8) return str;
  return `${str.slice(0, 4)}...${str.slice(-4)}`;
}

const missingConfigKeys = computed(() => {
  const root = getEnvRoot() || {};
  const result = [];
  for (const id of requiredKeys) {
    const flat = root[id];
    const alt = root[id.replace(/\./g, '_')] ?? root[id.toLowerCase()] ?? root[id.toUpperCase()];
    const val = flat ?? alt;
    if (val === undefined || val === null || val === '') {
      result.push({ id });
    }
  }
  return result;
});

const configuredConfigKeys = computed(() => {
  const root = getEnvRoot() || {};
  const result = [];
  for (const id of requiredKeys) {
    const flat = root[id];
    const alt = root[id.replace(/\./g, '_')] ?? root[id.toLowerCase()] ?? root[id.toUpperCase()];
    const val = flat ?? alt;
    if (val !== undefined && val !== null && val !== '') {
      result.push({ id, preview: pickPreview(val) });
    }
  }
  return result;
});

// 添加日志
function addLog(type, message) {
  recentLogs.value.unshift({
    id: ++logIdCounter,
    timestamp: Date.now(),
    type,
    message
  });
  
  // 只保留最近10条日志
  if (recentLogs.value.length > 10) {
    recentLogs.value = recentLogs.value.slice(0, 10);
  }
}

// 格式化时间
function formatTime(timestamp) {
  return new Date(timestamp).toLocaleTimeString();
}

// MD5哈希函数
function md5(string) {
  function md5cycle(x, k) {
    var a = x[0], b = x[1], c = x[2], d = x[3];
    a = ff(a, b, c, d, k[0], 7, -680876936);
    d = ff(d, a, b, c, k[1], 12, -389564586);
    c = ff(c, d, a, b, k[2], 17, 606105819);
    b = ff(b, c, d, a, k[3], 22, -1044525330);
    a = ff(a, b, c, d, k[4], 7, -176418897);
    d = ff(d, a, b, c, k[5], 12, 1200080426);
    c = ff(c, d, a, b, k[6], 17, -1473231341);
    b = ff(b, c, d, a, k[7], 22, -45705983);
    a = ff(a, b, c, d, k[8], 7, 1770035416);
    d = ff(d, a, b, c, k[9], 12, -1958414417);
    c = ff(c, d, a, b, k[10], 17, -42063);
    b = ff(b, c, d, a, k[11], 22, -1990404162);
    a = ff(a, b, c, d, k[12], 7, 1804603682);
    d = ff(d, a, b, c, k[13], 12, -40341101);
    c = ff(c, d, a, b, k[14], 17, -1502002290);
    b = ff(b, c, d, a, k[15], 22, 1236535329);
    a = gg(a, b, c, d, k[1], 5, -165796510);
    d = gg(d, a, b, c, k[6], 9, -1069501632);
    c = gg(c, d, a, b, k[11], 14, 643717713);
    b = gg(b, c, d, a, k[0], 20, -373897302);
    a = gg(a, b, c, d, k[5], 5, -701558691);
    d = gg(d, a, b, c, k[10], 9, 38016083);
    c = gg(c, d, a, b, k[15], 14, -660478335);
    b = gg(b, c, d, a, k[4], 20, -405537848);
    a = gg(a, b, c, d, k[9], 5, 568446438);
    d = gg(d, a, b, c, k[14], 9, -1019803690);
    c = gg(c, d, a, b, k[3], 14, -187363961);
    b = gg(b, c, d, a, k[8], 20, 1163531501);
    a = gg(a, b, c, d, k[13], 5, -1444681467);
    d = gg(d, a, b, c, k[2], 9, -51403784);
    c = gg(c, d, a, b, k[7], 14, 1735328473);
    b = gg(b, c, d, a, k[12], 20, -1926607734);
    a = hh(a, b, c, d, k[5], 4, -378558);
    d = hh(d, a, b, c, k[8], 11, -2022574463);
    c = hh(c, d, a, b, k[11], 16, 1839030562);
    b = hh(b, c, d, a, k[14], 23, -35309556);
    a = hh(a, b, c, d, k[1], 4, -1530992060);
    d = hh(d, a, b, c, k[4], 11, 1272893353);
    c = hh(c, d, a, b, k[7], 16, -155497632);
    b = hh(b, c, d, a, k[10], 23, -1094730640);
    a = hh(a, b, c, d, k[13], 4, 681279174);
    d = hh(d, a, b, c, k[0], 11, -358537222);
    c = hh(c, d, a, b, k[3], 16, -722521979);
    b = hh(b, c, d, a, k[6], 23, 76029189);
    a = hh(a, b, c, d, k[9], 4, -640364487);
    d = hh(d, a, b, c, k[12], 11, -421815835);
    c = hh(c, d, a, b, k[15], 16, 530742520);
    b = hh(b, c, d, a, k[2], 23, -995338651);
    a = ii(a, b, c, d, k[0], 6, -198630844);
    d = ii(d, a, b, c, k[7], 10, 1126891415);
    c = ii(c, d, a, b, k[14], 15, -1416354905);
    b = ii(b, c, d, a, k[5], 21, -57434055);
    a = ii(a, b, c, d, k[12], 6, 1700485571);
    d = ii(d, a, b, c, k[3], 10, -1894986606);
    c = ii(c, d, a, b, k[10], 15, -1051523);
    b = ii(b, c, d, a, k[1], 21, -2054922799);
    a = ii(a, b, c, d, k[8], 6, 1873313359);
    d = ii(d, a, b, c, k[15], 10, -30611744);
    c = ii(c, d, a, b, k[6], 15, -1560198380);
    b = ii(b, c, d, a, k[13], 21, 1309151649);
    a = ii(a, b, c, d, k[4], 6, -145523070);
    d = ii(d, a, b, c, k[11], 10, -1120210379);
    c = ii(c, d, a, b, k[2], 15, 718787259);
    b = ii(b, c, d, a, k[9], 21, -343485551);
    x[0] = add32(a, x[0]);
    x[1] = add32(b, x[1]);
    x[2] = add32(c, x[2]);
    x[3] = add32(d, x[3]);
  }
  function cmn(q, a, b, x, s, t) {
    a = add32(add32(a, q), add32(x, t));
    return add32((a << s) | (a >>> (32 - s)), b);
  }
  function ff(a, b, c, d, x, s, t) {
    return cmn((b & c) | ((~b) & d), a, b, x, s, t);
  }
  function gg(a, b, c, d, x, s, t) {
    return cmn((b & d) | (c & (~d)), a, b, x, s, t);
  }
  function hh(a, b, c, d, x, s, t) {
    return cmn(b ^ c ^ d, a, b, x, s, t);
  }
  function ii(a, b, c, d, x, s, t) {
    return cmn(c ^ (b | (~d)), a, b, x, s, t);
  }
  function md51(s) {
    var n = s.length,
        state = [1732584193, -271733879, -1732584194, 271733878], i;
    for (i = 64; i <= s.length; i += 64) {
      md5cycle(state, md5blk(s.substring(i - 64, i)));
    }
    s = s.substring(i - 64);
    var tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
    for (i = 0; i < s.length; i++)
      tail[i >> 2] |= s.charCodeAt(i) << ((i % 4) << 3);
    tail[i >> 2] |= 0x80 << ((i % 4) << 3);
    if (i > 55) {
      md5cycle(state, tail);
      for (i = 0; i < 16; i++) tail[i] = 0;
    }
    tail[14] = n * 8;
    md5cycle(state, tail);
    return state;
  }
  function md5blk(s) {
    var md5blks = [], i;
    for (i = 0; i < 64; i += 4) {
      md5blks[i >> 2] = s.charCodeAt(i)
        + (s.charCodeAt(i + 1) << 8)
        + (s.charCodeAt(i + 2) << 16)
        + (s.charCodeAt(i + 3) << 24);
    }
    return md5blks;
  }
  var hex_chr = '0123456789abcdef'.split('');
  function rhex(n) {
    var s = '', j = 0;
    for(; j < 4; j++)
      s += hex_chr[(n >> (j * 8 + 4)) & 0x0F]
        + hex_chr[(n >> (j * 8)) & 0x0F];
    return s;
  }
  function hex(x) {
    for (var i = 0; i < x.length; i++)
      x[i] = rhex(x[i]);
    return x.join('');
  }
  function add32(a, b) {
    return (a + b) & 0xFFFFFFFF;
  }
  return hex(md51(string));
}

// 测试连接
async function testConnection() {
  testing.value = true;
  testResult.value = null;
  
  try {
    // 构建基础API请求参数
    const baseUrl = MINGDAO_CONFIG.api.baseURL;
    const params = {
      appKey: MINGDAO_CONFIG.api.appKey,
      worksheetId: MINGDAO_CONFIG.api.worksheetId,
      pageSize: 1,
      pageIndex: 1
    };
    
    // 生成签名 - 明道云标准算法
    const sortedParams = Object.keys(params)
      .sort()
      .map(key => `${key}=${params[key]}`)
      .join('&');
    
    // 添加密钥并生成MD5签名
    const signString = sortedParams + MINGDAO_CONFIG.api.sign;
    addLog('info', `签名原串: ${signString}`);
    
    // 使用MD5生成签名
    params.sign = md5(signString).toUpperCase();
    addLog('info', `生成的签名: ${params.sign}`);
    
    const testUrl = `${baseUrl}/getFilterRows`;
    addLog('info', `测试API连接: POST ${testUrl}`);
    
    // 使用POST方法调用API
    const response = await fetch(testUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
      body: JSON.stringify(params)
    });
    
    const data = await response.json();
    
    if (data.success) {
      testResult.value = {
        success: true,
        message: `连接成功！返回 ${data.data?.length || 0} 条数据`
      };
      addLog('success', 'API连接测试成功');
    } else {
      testResult.value = {
        success: false,
        message: `API错误: ${data.error_msg || '未知错误'}`
      };
      addLog('error', `API错误: ${data.error_msg}`);
    }
    
  } catch (error) {
    testResult.value = {
      success: false,
      message: `连接失败: ${error.message}`
    };
    addLog('error', `连接失败: ${error.message}`);
  } finally {
    testing.value = false;
  }
}

// 键盘事件处理
function handleKeyDown(event) {
  // Ctrl + Shift + D 显示/隐藏调试面板
  if (event.ctrlKey && event.shiftKey && event.key === 'D') {
    event.preventDefault();
    showDebug.value = !showDebug.value;
    console.log('调试面板已', showDebug.value ? '显示' : '隐藏');
  }
  
  // 连续点击5次ESC键也可以显示调试面板
  if (event.key === 'Escape') {
    escKeyCount++;
    if (escKeyCount >= 5) {
      showDebug.value = true;
      escKeyCount = 0;
      console.log('通过ESC键激活调试面板');
    }
    setTimeout(() => { escKeyCount = 0; }, 2000); // 2秒后重置计数
  }
}

let escKeyCount = 0;

// 监听全局错误和日志
onMounted(() => {
  // 添加键盘事件监听
  document.addEventListener('keydown', handleKeyDown);
  
  // 拦截console.log输出
  const originalLog = console.log;
  const originalError = console.error;
  const originalWarn = console.warn;
  
  console.log = (...args) => {
    addLog('info', args.join(' '));
    originalLog.apply(console, args);
  };
  
  console.error = (...args) => {
    addLog('error', args.join(' '));
    originalError.apply(console, args);
  };
  
  console.warn = (...args) => {
    addLog('warning', args.join(' '));
    originalWarn.apply(console, args);
  };
});

// 清理事件监听器
onUnmounted(() => {
  document.removeEventListener('keydown', handleKeyDown);
});

// 暴露给父组件使用
defineExpose({
  addLog,
  showDebug
});
</script>

<style scoped>
.debug-panel {
  position: fixed;
  top: 20px;
  right: 20px;
  width: 400px;
  max-height: 80vh;
  background: #fff;
  border: 2px solid #f8b300;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  z-index: 1000;
  overflow-y: auto;
}

.debug-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #f8b300;
  color: #000;
  padding: 12px 16px;
  font-weight: 600;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  padding: 0;
  line-height: 1;
}

.debug-section {
  padding: 16px;
  border-bottom: 1px solid #eee;
}

.debug-section:last-child {
  border-bottom: none;
}

.debug-section h4 {
  margin: 0 0 12px 0;
  font-size: 14px;
  color: #333;
}

.status-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 6px 0;
  font-size: 13px;
}

.status-item.success {
  color: #28a745;
}

.status-item.error {
  color: #dc3545;
}

.error-details {
  margin-top: 8px;
  padding: 8px;
  background: #f8d7da;
  border-radius: 4px;
  font-size: 12px;
  color: #721c24;
}

.field-list {
  max-height: 200px;
  overflow-y: auto;
}

.field-item {
  display: grid;
  grid-template-columns: 1fr 2fr auto;
  gap: 8px;
  padding: 4px 0;
  font-size: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.field-item.configured {
  color: #28a745;
}

.field-item.missing {
  color: #dc3545;
}

.field-name {
  font-weight: 600;
}

.field-value {
  font-family: 'Courier New', monospace;
  font-size: 11px;
  word-break: break-all;
}

.test-btn {
  background: #f8b300;
  color: #000;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  font-weight: 600;
}

.test-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.test-result {
  margin-top: 8px;
  padding: 8px;
  border-radius: 4px;
  font-size: 12px;
}

.test-result.success {
  background: #d4edda;
  color: #155724;
}

.test-result.error {
  background: #f8d7da;
  color: #721c24;
}

.missing-list {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.missing-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 6px 8px;
  background: #fff5f5;
  border: 1px solid #ffd6d6;
  border-radius: 6px;
  font-size: 12px;
}

.missing-id {
  font-family: 'Courier New', monospace;
  color: #dc3545;
}

.missing-tip {
  color: #dc3545;
  font-weight: 700;
}

.configured-list {
  margin-top: 10px;
}

.configured-item {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 8px;
  padding: 4px 0;
  font-size: 12px;
}

.cfg-id {
  font-family: 'Courier New', monospace;
  color: #333;
}

.cfg-value {
  font-family: 'Courier New', monospace;
  color: #666;
}

.logs {
  max-height: 150px;
  overflow-y: auto;
  font-size: 11px;
  font-family: 'Courier New', monospace;
}

.log-item {
  display: flex;
  gap: 8px;
  padding: 2px 0;
  border-bottom: 1px solid #f5f5f5;
}

.log-time {
  color: #666;
  min-width: 60px;
}

.log-message {
  flex: 1;
  word-break: break-word;
}

.log-item.info {
  color: #0066cc;
}

.log-item.success {
  color: #28a745;
}

.log-item.error {
  color: #dc3545;
}

.log-item.warning {
  color: #856404;
}

.debug-toggle {
  position: fixed;
  bottom: 20px;
  right: 20px;
  background: #f8b300;
  color: #000;
  border: none;
  padding: 12px 16px;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 600;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  z-index: 999;
}

.debug-toggle:hover {
  background: #e0a200;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .debug-panel {
    width: calc(100vw - 40px);
    top: 10px;
    right: 20px;
    left: 20px;
  }
}
</style>